package com.study.lihan.letcode.offer;

import javax.xml.ws.soap.Addressing;

/**
 * @Author: lihan
 * @Date : 2022/9/22- 09
 * @DESCRIPTION: com.study.lihan.letcode.offer
 * 题目：输入两个表示二进制的字符串，请计算它们的和，并以二进制字符串的形式输出。例如，输入的二进制字符串分别是"11"和"10"，则输出"101"。
 * @version: 1.0
 */
public class T2 {
    public static void main(String[] args) {
        String op1 = "1";
        String op2 = "111";
       String result = add(op1, op2);
        System.out.println(result);

    }
    public static String add(String op1, String op2){
        StringBuilder stringBuilder = new StringBuilder();
        int index1 = op1.length()-1;
        int index2 = op2.length()-1;
        int val1 = 0;
        int val2 = 0;
        int pow = 0;
        while (index1 >= 0 && index2 >= 0){
            val1 = Integer.valueOf(op1.charAt(index1))-48;  //如何取出指定索引值的字符串
            val2 = Integer.valueOf(op2.charAt(index2))-48;
            int acc = val1 + val2 + pow;
            pow = acc/2;
            int cur = acc%2;
            stringBuilder.append(cur);
            index1--;
            index2--;
        }
        while (index1 >= 0){
            val1 = Integer.valueOf(op1.charAt(index1))-48;
            int acc = val1  + pow;
            pow = acc/2;
            int cur = acc%2;
            stringBuilder.append(cur);
            index1--;
        }
        while (index2 >= 0){
            val2 = Integer.valueOf(op2.charAt(index2))-48;
            int acc =   val2 + pow;
            pow = acc/2;
            int cur = acc%2;
            stringBuilder.append(cur);
            index2--;
        }
        if (pow == 1){
            stringBuilder.append(1);
        }

        return stringBuilder.reverse().toString();
    }
}
